package com.ysxsoft.wdg.ui.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.RadioGroup;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.ysxsoft.wdg.MyApplication;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.FragmentAdapter;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.base.BaseFragment;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.event.CommentEvent;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.pay.PayResultListener;
import com.ysxsoft.wdg.ui.activity.center_zy.ZySearchListActivity;
import com.ysxsoft.wdg.ui.activity.home.TbSearchListActivity;
import com.ysxsoft.wdg.ui.fragment.CenterFragment;
import com.ysxsoft.wdg.ui.fragment.MyFragment;
import com.ysxsoft.wdg.ui.fragment.HTaoFragment;
import com.ysxsoft.wdg.ui.fragment.HomeFragment;
import com.ysxsoft.wdg.ui.fragment.THuiFragment;
import com.ysxsoft.wdg.ui.fragment.THuiWebFragment;
import com.ysxsoft.wdg.ui.fragment.TTaoWebFragment;
import com.ysxsoft.wdg.upversion.ApkUpdateService;
import com.ysxsoft.wdg.upversion.MyProgressDialog;
import com.ysxsoft.wdg.upversion.VersionBean;
import com.ysxsoft.wdg.util.SystemUtils;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.widget.ActivityDialog;
import com.ysxsoft.wdg.widget.alertview.AlertViewFactory;
import com.ysxsoft.wdg.widget.alertview.OnItemClickListener;
import com.ysxsoft.wdg.widget.viewpager.NoScrollViewPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.ysxsoft.wdg.bean.event.CommentEvent.EventStatus.APK_update;
import static com.ysxsoft.wdg.bean.event.CommentEvent.EventStatus.MAIN_finish;


public class MainActivity extends BaseActivity {

    THuiWebFragment fragment;
    TTaoWebFragment fragment2;

    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    @BindView(R.id.view_pager)
    NoScrollViewPager viewPager;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;

    private List<BaseFragment> mFragmentList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        radioGroup.getChildAt(0).setSelected(true);
        mFragmentList = new ArrayList<>();

        HomeFragment homeFragment = new HomeFragment();
        homeFragment.setOnHomeChangeListener(new HomeFragment.OnHomeChangeListener() {
            @Override
            public void toCenter() {
                changeFragment(2);
            }

            @Override
            public void toTeHui() {
                changeFragment(1);
            }
        });

        fragment = new THuiWebFragment();
        fragment2 = new TTaoWebFragment();

        mFragmentList.add(homeFragment);//首页
        mFragmentList.add(fragment);//特惠区
        mFragmentList.add(new CenterFragment());//商城
        mFragmentList.add(fragment2);//汇淘
        mFragmentList.add(new MyFragment());//我的
        FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), mFragmentList);
        viewPager.setAdapter(fragmentAdapter);
        viewPager.setOffscreenPageLimit(mFragmentList.size());

        for (int i = 0; i < radioGroup.getChildCount(); i++) {
            final int finalI = i;
            radioGroup.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    changeFragment(finalI);
                }
            });
        }

        getVersion();
        requestPermissions();

    }

    private void requestPermissions() {//请求权限
        new RxPermissions(MainActivity.this)
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        // All requested permissions are granted
                    } else {
                        // At least one permission is denied
                        ToastUtils.showToast("禁用某个权限会导致部分功能不可用！");
                    }
                });
    }

    private void getVersion() {
        final int curCode = SystemUtils.getVersionCode(this);
        mApiHelper.getVersion(new Observer<BaseBean<VersionBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<VersionBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    VersionBean dataBean = baseBean.getData();
                    ApkUpdateService.APK_UPDATE = dataBean.getPath();

                    int verCode = Integer.parseInt(dataBean.getVercode());
                    if (verCode > curCode) {
                        handler.sendEmptyMessage(2);
                    }
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }

    @Override
    protected void setListener() {
    }

    public void changeFragment(int tarIndex) {
        viewPager.setCurrentItem(tarIndex);
        for (int i = 0; i < mFragmentList.size(); i++) {
            radioGroup.getChildAt(i).setSelected(i == tarIndex);
        }
        if (tarIndex == 1) {
            fragment.reset();
        }
        if (tarIndex == 3) {
            fragment2.reset();
        }
    }


    @Subscribe
    public void getEvent(CommentEvent event) {
        int code = event.getCode();
        if (code == MAIN_finish) {
            finish();
        } else if (code == APK_update) {
            if (isFront) {
                handler.sendEmptyMessage(0);
            }
        }
    }


    private long time = -1;

    @Override
    public void onBackPressed() {
        if(viewPager.getCurrentItem()==1){
            if(fragment.canGoBack()){
                fragment.goBack();
            }else{
                if (System.currentTimeMillis() - time > 2000) {
                    ToastUtils.showToast("再次点击退出应用");
                    time = System.currentTimeMillis();
                } else {
                    super.onBackPressed();
                }
            }
        }else if(viewPager.getCurrentItem()==3){
            if(fragment2.canGoBack()){
                fragment2.goBack();
            }else{
                if (System.currentTimeMillis() - time > 2000) {
                    ToastUtils.showToast("再次点击退出应用");
                    time = System.currentTimeMillis();
                } else {
                    super.onBackPressed();
                }
            }
        }else{
            if (System.currentTimeMillis() - time > 2000) {
                ToastUtils.showToast("再次点击退出应用");
                time = System.currentTimeMillis();
            } else {
                super.onBackPressed();
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        MyApplication.getInstance().exitApp();
    }


    /*************************   版本更新    *****************************/
    private MyProgressDialog progressDialog;
    private boolean isFront = false;

    @Override
    public void onResume() {
        super.onResume();
        isFront = true;

        String t=getText();
        if(!"".equals(t)) {
            if ("".equals(keyword)) {
                keyword = t;
                showDialog();
            } else {
                if (!keyword.equals(t)) {//剪切板里边的一样不处理
                    keyword = t;
                    showDialog();
                }
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        isFront = false;
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    showProgressDialog();
                    break;
                case 2:
                    showUpView();
                    break;
            }
        }
    };

    private void showProgressDialog() {
        if (progressDialog != null) {
            progressDialog = null;
        }
        progressDialog = new MyProgressDialog();
        progressDialog.show(getSupportFragmentManager(), "progress");
    }

    private void showUpView() {
        AlertViewFactory.getInstance().getUpdateApkAlert(mContext, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {

                    new RxPermissions(MainActivity.this)
                            .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean aBoolean) throws Exception {
                                    ToastUtils.showToast("开始下载");
                                    Intent intent = new Intent(MainActivity.this, ApkUpdateService.class);
                                    startService(intent);
                                }
                            });
                }
            }
        }).show();
    }

    /*************************   版本更新    *****************************/

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if (intent.getBooleanExtra("p", false)) {
            changeFragment(1);
        }
    }

    /**
     * 弹出活动
     */
    private void showDialog() {
        ActivityDialog dialog = new ActivityDialog(this, R.style.CenterDialogStyle);
        dialog.setText(keyword);
        dialog.setListener(new ActivityDialog.OnDialogClickListener() {
            @Override
            public void lookDetail() {
//                ZySearchListActivity.start(MainActivity.this,keyword);
                TbSearchListActivity.start(mContext,keyword);
            }
        });
        dialog.showDialog();
    }


    private String getText() {
        String content="";
        ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData data = cm.getPrimaryClip();
        if(data!=null&&!"".equals(data)){
            ClipData.Item item = data.getItemAt(0);
            content = item.getText().toString();
        }
        return content;
    }

    private String keyword = "";

    public void showMPage(){
        if(fragment==null){
            return;
        }
        changeFragment(1);
        fragment.showMPage();
    }

    public void showTPage(){
        if(fragment==null){
            return;
        }
        changeFragment(1);
        fragment.showTPage();
    }

}
